package thread;


import java.util.PriorityQueue;

/*
 * @author zzr
 * @date: 2025/04/17  23:21
 * @description:
 */
class MyTimerTask implements Comparable<MyTimerTask>, Runnable {

    private long time;
    Runnable runnable = null;

    public MyTimerTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public void run() {
        runnable.run();
    }
    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }
}

class MyTimer {

    // 负责扫描队列
    Thread t = null;

    PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();

    Object locker = new Object();
    public void schedule (Runnable runnable, long dealy) {
        synchronized (locker) {
            MyTimerTask myTimerTask = new MyTimerTask(runnable, dealy);
            queue.offer(myTimerTask);
            locker.notify();
        }
    }

    public MyTimer() {
        t = new Thread(() -> {
            while (true) {
                try {
                    synchronized (locker) {
                        while (queue.isEmpty()) {
                            // 等待
                            locker.wait();
                        }
                        MyTimerTask myTimerTask = queue.peek();

                        long curTime = System.currentTimeMillis();
                        if (curTime >= myTimerTask.getTime()) {
                            queue.poll();
                            myTimerTask.run();

                        } else {
                            // 时间还没到 暂不执行
                            locker.wait(myTimerTask.getTime() - curTime);
                            if (curTime >= myTimerTask.getTime()) {
                                queue.poll();
                                myTimerTask.run();
                            }
                        }
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t.start();
    }
}
public class Thread22 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello myTimer");
            }
        },2000);
    }
}
